package io.gitee.cikai;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.PushBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

/**
 * HTTP2接口示例，返回服务器当前时间
 *
 * @author cikai <cikai0923@foxmail.com>
 * @date 04/22/2022
 */
@RestController
public class TimeController {

    /**
     * curl -Ik --http2 https://127.0.0.1:8443/time
     *
     * @return 服务器当前时间
     */
    @GetMapping("/time")
    public String time() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        return sdf.format(System.currentTimeMillis());
    }

    @GetMapping("/time/push")
    public void http2ServerPush(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        PushBuilder pushBuilder = request.newPushBuilder();
        pushBuilder
                .path("/")
                .addHeader("content-type", "text/plain")
                .push();
        PrintWriter respWriter = response.getWriter();
        respWriter.write(sdf.format(System.currentTimeMillis()));
    }
}
